package com.naughty.shopapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.naughty.shopapi.mapper.CategoriesMapper;
import com.naughty.shopapi.mapper.CommentsMapper;
import com.naughty.shopapi.mapper.GoodsMapper;
import com.naughty.shopapi.mapper.UsersMapper;
import com.naughty.shopapi.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "商品相关操作")
@RestController
@RequestMapping("api")
public class GoodsController {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private CategoriesMapper categoriesMapper;

    /**
     * 商品详情API
     *
     * @param good 商品ID
     * @return
     */

    @ApiOperation("获取商品详情")
    @GetMapping("/goods/{good}")
    public ResponseEntity<Object> getGoodsDetail(@PathVariable("good") Integer good) {

        final GoodsDetailVO goodsDetailVO = new GoodsDetailVO();//最外层
        final GoodsCommentDetailVO goodsCommentDetailVO = new GoodsCommentDetailVO();//goods层
        final List<UserCommentVO> CommentOUT = new ArrayList<>();//放置所有评论
        final List<Goods> LikeGoodOut = new ArrayList<>();//放置所有评论
        /**
         * 搜索指定id商品，并填充
         */
        final QueryWrapper<Goods> wrapperGoodId = new QueryWrapper<>();
        wrapperGoodId.eq("id", good);
        List<Goods> objGood = goodsMapper.selectList(wrapperGoodId);
        goodsCommentDetailVO.setId(objGood.get(0).getId());
        goodsCommentDetailVO.setUser_id(objGood.get(0).getUser_id());
        goodsCommentDetailVO.setCategory_id(objGood.get(0).getCategory_id());
        goodsCommentDetailVO.setTitle(objGood.get(0).getTitle());
        goodsCommentDetailVO.setDescription(objGood.get(0).getDescription());
        goodsCommentDetailVO.setPrice(objGood.get(0).getPrice());
        goodsCommentDetailVO.setStock(objGood.get(0).getStock());
        goodsCommentDetailVO.setSales(objGood.get(0).getSales());
        goodsCommentDetailVO.setCover(objGood.get(0).getCover());
        goodsCommentDetailVO.setPics(objGood.get(0).getPics());
        goodsCommentDetailVO.setIs_on(objGood.get(0).getIs_on());
        goodsCommentDetailVO.setIs_recommend(objGood.get(0).getIs_recommend());
        goodsCommentDetailVO.setDetails(objGood.get(0).getDetails());
        goodsCommentDetailVO.setCreated_at(objGood.get(0).getCreated_at());
        goodsCommentDetailVO.setUpdated_at(objGood.get(0).getUpdated_at());
        goodsCommentDetailVO.setCollects_count(objGood.get(0).getCollects_count());
        goodsCommentDetailVO.setCover_url(objGood.get(0).getCover_url());
        goodsCommentDetailVO.setPics_url(objGood.get(0).getPics_url());
        goodsCommentDetailVO.setIs_collect(objGood.get(0).getIs_collect());

        final QueryWrapper<Comments> wrapperCommentGoodId = new QueryWrapper<>();
        wrapperCommentGoodId.eq("goods_id", good);
        List<Comments> objCommentGoodId = commentsMapper.selectList(wrapperCommentGoodId);
        /**
         * 循环所有评论，将每一个评论创建一个object，并将对应的User存放进去
         */
        for (int i = 0; i < objCommentGoodId.size(); i++) {//所有评论
            final UserCommentVO userCommentVO = new UserCommentVO();//商品详情包含的评论层
            final QueryWrapper<Users> wrapperChildren = new QueryWrapper<>();
            wrapperChildren.eq("id", Integer.parseInt(String.valueOf(objCommentGoodId.get(i).getUser_id())));
            final Users userComment = new Users();
            final List<Users> userList = usersMapper.selectList(wrapperChildren);
            userComment.setId(userList.get(0).getId());
            userComment.setName(userList.get(0).getName());
            userComment.setAvatar(userList.get(0).getAvatar());
            userComment.setAvatar_url(userList.get(0).getAvatar_url());
            userComment.setPhone(userList.get(0).getPhone());
            userComment.setEmail(userList.get(0).getEmail());
            userComment.setIs_locked(userList.get(0).getIs_locked());
            userComment.setOpenid(userList.get(0).getOpenid());
            userComment.setCreated_at(userList.get(0).getCreated_at());
            userComment.setUpdated_at(userList.get(0).getUpdated_at());

            userCommentVO.setId(objCommentGoodId.get(i).getId());
            userCommentVO.setUser_id(objCommentGoodId.get(i).getUser_id());
            userCommentVO.setOrder_id(objCommentGoodId.get(i).getOrder_id());
            userCommentVO.setGoods_id(objCommentGoodId.get(i).getGoods_id());
            userCommentVO.setRate(objCommentGoodId.get(i).getRate());
            userCommentVO.setStar(objCommentGoodId.get(i).getStar());
            userCommentVO.setContent(objCommentGoodId.get(i).getContent());
            userCommentVO.setReply(objCommentGoodId.get(i).getReply());
            userCommentVO.setPics(objCommentGoodId.get(i).getPics());
            userCommentVO.setPics_url(objCommentGoodId.get(i).getPics_url());
            userCommentVO.setCreated_at(objCommentGoodId.get(i).getCreated_at());
            userCommentVO.setUpdated_at(objCommentGoodId.get(i).getUpdated_at());
            userCommentVO.setUser(userComment);
            CommentOUT.add(userCommentVO);
        }
        goodsCommentDetailVO.setComments(CommentOUT);//带user的评论
        /**
         * 查找同类型商品，在这里用category_id判断
         */
        final Integer likeCategoryId = objGood.get(0).getCategory_id();
        final QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", likeCategoryId);
        final List<Goods> likeGoodsList = goodsMapper.selectList(wrapper);
        for (int i = 0; i < likeGoodsList.size(); i++) {
            final Goods likeGoods = new Goods();//likesgoods层
            likeGoods.setId(likeGoodsList.get(i).getId());
            likeGoods.setUser_id(likeGoodsList.get(i).getUser_id());
            likeGoods.setCategory_id(likeGoodsList.get(i).getCategory_id());
            likeGoods.setTitle(likeGoodsList.get(i).getTitle());
            likeGoods.setDescription(likeGoodsList.get(i).getDescription());
            likeGoods.setPrice(likeGoodsList.get(i).getPrice());
            likeGoods.setStock(likeGoodsList.get(i).getStock());
            likeGoods.setSales(likeGoodsList.get(i).getSales());
            likeGoods.setCover(likeGoodsList.get(i).getCover());
            likeGoods.setPics(likeGoodsList.get(i).getPics());
            likeGoods.setIs_on(likeGoodsList.get(i).getIs_on());
            likeGoods.setIs_recommend(likeGoodsList.get(i).getIs_recommend());
            likeGoods.setDetails(likeGoodsList.get(i).getDetails());
            likeGoods.setCreated_at(likeGoodsList.get(i).getCreated_at());
            likeGoods.setUpdated_at(likeGoodsList.get(i).getUpdated_at());
            likeGoods.setCollects_count(likeGoodsList.get(i).getCollects_count());
            likeGoods.setCover_url(likeGoodsList.get(i).getCover_url());
            likeGoods.setPics_url(likeGoodsList.get(i).getPics_url());
            likeGoods.setIs_collect(likeGoodsList.get(i).getIs_collect());

            LikeGoodOut.add(likeGoods);
        }

        goodsDetailVO.setGoods(goodsCommentDetailVO);
        goodsDetailVO.setLike_goods(LikeGoodOut);
        return new ResponseEntity<>(goodsDetailVO, HttpStatus.OK);
    }

    /**
     * 商品列表API，分别展示商品列表(同首页商品列表)及分类商品列表(同首页商品分类)，通过这7个参数进行一个总控
     * <p>
     * 注意：sales recommend price comments_count 这四个排序字段，每次只传一个， 值为1。
     * 也可以四个参数都传，但是只能有一个值为1， 其他的为0。如果有多个参数的值为1， 结果可能不会达到预期。
     * <p>
     * 倒序--->从大到小
     *
     * @param page           分页
     * @param title          商品名模糊搜索
     * @param category_id    分类搜索
     * @param sales          销量排序，值为1， 倒序
     * @param recommend      推荐， 值为1，获取推荐商品
     * @param price          价格排序，值为1， 倒序
     * @param comments_count 评论数排序，值为1， 倒序
     * @return
     */
    @ApiOperation("获取商品列表")
    @GetMapping("/goods")
    public ResponseEntity<Object> getGoodsList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(required = false) String title,
            @RequestParam(defaultValue = "0") Integer category_id,
            @RequestParam(defaultValue = "0") Integer sales,
            @RequestParam(defaultValue = "0") Integer recommend,
            @RequestParam(defaultValue = "0") Integer price,
            @RequestParam(defaultValue = "0") Integer comments_count
    ) {
        //正负值处理
        int pageAbs = 1;
        int categoryIdAbs = 0;
        int salesAbs = 0;
        int recommendAbs = 0;
        int priceAbs = 0;
        int commentsCountAbs = 0;
        //参数正负过滤
        if (page <= 1) {
            pageAbs = 1;
        } else {
            pageAbs = Math.abs(page);
        }
        if (category_id <= 0) {
            categoryIdAbs = 0;
        } else {
            categoryIdAbs = Math.abs(category_id);
        }
        if (sales <= 0) {
            salesAbs = 0;
        } else {
            salesAbs = Math.abs(sales);
        }

        if (recommend <= 0) {
            recommendAbs = 0;
        } else {
            recommendAbs = Math.abs(recommend);
        }

        if (price <= 0) {
            priceAbs = 0;
        } else {
            priceAbs = Math.abs(price);
        }
        if (comments_count <= 0) {
            commentsCountAbs = 0;
        } else {
            commentsCountAbs = Math.abs(comments_count);
        }

        /**
         *  category字段不受任何参数影响，为全部分类输出
         *  参数影响goods字段及recommend_goods字段
         */
        final GoodsListVO goodsListVO = new GoodsListVO();
        List<CategoriesVO> categoriesOUT = new ArrayList<>();   //分类字段外层

        //分类参数构造
        final QueryWrapper<Categories> wrapperFather = new QueryWrapper<>();
        wrapperFather.eq("pid", 0);
        List<Categories> objsFather = categoriesMapper.selectList(wrapperFather);
        for (int i = 0; i < objsFather.size(); i++) {
            CategoriesVO categoriesVO = new CategoriesVO();
            final QueryWrapper<Categories> wrapperChildren = new QueryWrapper<>();
            wrapperChildren.eq("pid", Integer.parseInt(String.valueOf(objsFather.get(i).getId())));
            categoriesVO.setChildren(categoriesMapper.selectList(wrapperChildren));
            categoriesVO.setId(objsFather.get(i).getId());
            categoriesVO.setPid(objsFather.get(i).getPid());
            categoriesVO.setName(objsFather.get(i).getName());
            categoriesVO.setLevel(objsFather.get(i).getLevel());
            categoriesVO.setStatus(objsFather.get(i).getStatus());
            categoriesOUT.add(categoriesVO);
        }

        //根据各参数条件构造
        final QueryWrapper<Goods> wrapperGoodsData = new QueryWrapper<>();
        if (categoryIdAbs != 0) {
            wrapperGoodsData.eq("category_id", categoryIdAbs);// .orderByDesc("created_at");
        }
        if (title != null) {
            wrapperGoodsData.like("title", title);
        }
        if (salesAbs == 0) {
            wrapperGoodsData.orderByAsc("sales");//--降序--从小到大
        } else {
            wrapperGoodsData.orderByDesc("sales");//--升序--从大到小
        }
        if (recommendAbs == 0) {
            wrapperGoodsData.orderByAsc("is_recommend");
        } else {
            wrapperGoodsData.orderByDesc("is_recommend");
        }
        if (priceAbs == 0) {
            wrapperGoodsData.orderByAsc("price");
        } else {
            wrapperGoodsData.orderByDesc("price");
        }
        if (commentsCountAbs == 0) {
            wrapperGoodsData.orderByAsc("comments_count");
        } else {
            wrapperGoodsData.orderByDesc("comments_count");
        }

        final GoodsVO goodsVO = new GoodsVO();
        String path = "http://localhost:8182/api/goods";
        //new Page<>()参数1：当前页，参数2：页面内容数量 -> 默认页面1，条数10
        final Page<Goods> goodsPage = new Page<>(pageAbs, 10);
        goodsMapper.selectPage(goodsPage, wrapperGoodsData);

        goodsVO.setCurrent_page(pageAbs);
        goodsVO.setData(goodsPage.getRecords());//https://api.shop.eduwork.cn/api/goods?category_id=0&recommend=0&page=1
        goodsVO.setFirst_page_url(path + "?recommend=" + recommendAbs + "&category_id=" + categoryIdAbs + "&page=1");
        goodsVO.setFrom(((pageAbs - 1) * 10) + 1);
        goodsVO.setNext_page_url(path + "?recommend=" + recommendAbs + "&category_id=" + categoryIdAbs + "&page=" + (pageAbs + 1));
        goodsVO.setPath(path);
        goodsVO.setPer_page(10);
        if (page <= 1) {
            goodsVO.setPrev_page_url(null);
        } else {
            goodsVO.setPrev_page_url(path + "?recommend=" + recommendAbs + "&category_id=" + categoryIdAbs + "&page=" + (pageAbs - 1));
        }
        goodsVO.setTo(pageAbs * 10);


        goodsListVO.setGoods(goodsVO);
        goodsListVO.setRecommend_goods(goodsPage.getRecords());
        goodsListVO.setCategories(categoriesOUT);
        return new ResponseEntity<>(goodsListVO, HttpStatus.OK);
    }

}
